package com.drakulo.hi.logic.io;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Element;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.tiled.TiledMap;

public class DataLoader {
	private static final String LUNCHER_FILE = "luncher.xml";

	private static final String START_MAP = "start-map";
	private static final String MAPS = "maps";
	private static final String MAP = "map";
	private static final String MAP_ID = "map-id";
	private static final String MAP_TILESET = "map-tileset";

	private String contentFolder;
	private Map<Integer, String> tileSets;
	private Integer currentMapId;

	public DataLoader(String p_folder) throws Exception {
		this.tileSets = new HashMap<Integer, String>();

		this.contentFolder = p_folder;

		Element root = FileHelper.loadXMLFile(p_folder + LUNCHER_FILE);
		loadMaps(root.getChild(MAPS));

		this.currentMapId = Integer.valueOf(root.getChild(START_MAP).getValue());
	}

	public TiledMap getCurrentTiledMap() throws SlickException {
		return new TiledMap(this.tileSets.get(this.currentMapId));
	}

	@SuppressWarnings("unchecked")
	private void loadMaps(Element p_maps) {
		List<Element> maps = p_maps.getChildren(MAP);
		for (Element map : maps) {
			Integer id = Integer.valueOf(map.getChild(MAP_ID).getValue());
			String tileset = map.getChild(MAP_TILESET).getValue();
			this.tileSets.put(id, this.contentFolder + tileset);
		}
	}
}
